package com.hk.kindheartedness;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.model.vo.DoctorVo;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 管理员对医生管理层
 */
public class DockerAdminActivity extends AppCompatActivity implements View.OnClickListener {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    //    Initialize ListView
    private ListView queryDoctorListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_docker_admin);
//        实例化
        dbOpenHelper = new DBOpenHelper(DockerAdminActivity.this, "db_kindheartedness", null, 1);
        //        获取按钮控制权
        Button doctorAddBtn = findViewById(R.id.doctorAddBtn);
        doctorAddBtn.setOnClickListener(this);
//        获取listView控制权
        queryDoctorListView = findViewById(R.id.queryDoctorListView);
//        渲染所有医生
        /**
         * 查询出所有的医生信息并进行回显
         */
        findAllDoctor();
        //        添加长按点击弹出选项框菜单
        queryDoctorListView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("选择操作！");
                menu.add(0, 0, 0, "详情");
                menu.add(0, 1, 0, "删除");
            }
        });
    }

    /**
     * 获取所有的医生
     */
    @SuppressLint("LongLogTag")
    private void findAllDoctor() {
//        获取打开的数据库
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("user", null, "type = ? ", new String[]{"1"}, null, null, null);
        //        存储获取到的数据
        List<Map<String, Object>> resultList = new ArrayList<>(10);
        while (cursor.moveToNext()) {
            Map<String, Object> map = new HashMap<>(8);
            String doctorName = cursor.getString(1);
            String createTime = cursor.getString(11);
            Integer doctorId = null;
            try {
                doctorId = Integer.valueOf(cursor.getString(10));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Log.e("DockerAdminActivity.java", "数据不能转化为数字,请检查！");
            }
            if (doctorId == null) {
                toast = ToastUtil.toastHint(toast, DockerAdminActivity.this, "暂时没有找到医生详情，请稍后查看！");
                return;
            }
//            根据医生ID查询医生详情
            Cursor queryDoctor = readableDatabase.query("doctor_details", null, "id = ? ", new String[]{doctorId.toString()}, null, null, null);
            Integer positionId = null,departmentsId = null;
            while (queryDoctor.moveToNext()) {
                try {
                    positionId = Integer.valueOf(queryDoctor.getString(2));
                    departmentsId = Integer.valueOf(queryDoctor.getString(3));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    Log.e("DockerAdminActivity.java", "数据不能转化为数字,请检查！");
                }
            }
            String positionName = null,departmentsName = null;
            if (positionId != null && departmentsId != null) {
//            根据职务ID查询医生职务
                Cursor queryPosition = readableDatabase.query("position", null, "id = ? ", new String[]{positionId.toString()}, null, null, null);
                while (queryPosition.moveToNext()) {
                    positionName = queryPosition.getString(1);
                }
//              根据科室ID查询医生所在科室名称
                Cursor queryDepartments = readableDatabase.query("departments", null, "id = ? ", new String[]{departmentsId.toString()}, null, null, null);
                while (queryDepartments.moveToNext()) {
                    departmentsName = queryDepartments.getString(1);
                }
            } else {
                toast = ToastUtil.toastHint(toast, DockerAdminActivity.this, "暂时没有找到医生对应职务或所属科室，请稍后查看！");
                return;
            }
//                对数据进行封装
            map.put("doctorId", doctorId);
            map.put("doctorName", doctorName);
            map.put("positionName", positionName);
            map.put("departmentsName", departmentsName);
            map.put("createTime", createTime);
//                将封装的map集合存储到resultList集合中
            resultList.add(map);
        }
//        判断是否具有医生
        if (resultList == null || resultList.size() == 0) {
            toast = ToastUtil.toastHint(toast, DockerAdminActivity.this, "暂时没有医生，请稍后查看！");
            return;
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                DockerAdminActivity.this,
                resultList,
                R.layout.query_doctor,
                new String[]{
                        "doctorId",
                        "doctorName", "positionName",
                        "departmentsName", "createTime"
                },
                new int[]{
                        R.id.doctorId,
                        R.id.doctorName, R.id.positionName,
                        R.id.departmentsName, R.id.createTime
                }
        );
        queryDoctorListView.setAdapter(simpleAdapter);
    }

    /**
     * 给菜单项添加事件
     *
     * @param item 菜单索引
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
//        获取上下文
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
//        得到listView中选择的条目绑定的Id
        String id = String.valueOf(info.id);
//        得到列表子节点的视图
        View targetView = info.targetView;
        //                获取单列 某一元素的控制权
        TextView doctorId = targetView.findViewById(R.id.doctorId);
//                获取元素内容 手机号
        String doctorIdToString = doctorId.getText().toString();
        Log.i("=====ListView列表绑定的ID==", id);
        Log.i("===== 对应的医生Id==", doctorIdToString);
        switch (item.getItemId()) {
            case 0:
//                更新事件的方法
                updateDiaLog(doctorIdToString);
                return true;
            case 1:
//                删除事件的方法
                deleteData(doctorIdToString);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    /**
     * 删除医生信息
     * @param doctorIdToString
     */
    private void deleteData(final String doctorIdToString) {
        //        建立一个对话框
//                添加一个弹出对话框
        AlertDialog alertDialog = new AlertDialog.Builder(DockerAdminActivity.this).create();
//                设置提示
        alertDialog.setMessage("确定要删除该采购员吗？");
//                设置 确认按钮操作
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
                int deleteUser = readableDatabase.delete("user", "doctor_id = ?", new String[]{doctorIdToString});
                int deleteDoctor = readableDatabase.delete("doctor_details", "id = ?", new String[]{doctorIdToString});
                if (deleteUser >= 1 && deleteDoctor >= 1) {
                    Log.i("BuyerAdminActivity.java", "删除成功,删除记录数：" + deleteDoctor);
                    toast = ToastUtil.toastHint(toast, DockerAdminActivity.this, "删除成功！");
                    startActivityForResult(new Intent(DockerAdminActivity.this, DockerAdminActivity.class), RESULT_OK);
                    finish();
                    return;
                }
                toast = ToastUtil.toastHint(toast, DockerAdminActivity.this, "删除失败,请刷新重试！");
                return;
            }
        });
//        设置取消按钮操作
        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                toast = ToastUtil.toastHint(toast, DockerAdminActivity.this, "本次操作已取消！");
                return;
            }
        });
//          显示对话框
        alertDialog.show();
    }

    /**
     * 更新医生信息
     * @param doctorIdToString 医生ID
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @SuppressLint("LongLogTag")
    private void updateDiaLog(String doctorIdToString) {
//        打开数据库
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//        封装回显所需信息
        DoctorVo doctorVo = null;
//        通过类型和医生ID查询基本信息
        Cursor cursorUser = readableDatabase.query("user", null, "type = ? and doctor_id = ?  ", new String[]{"1",doctorIdToString}, null, null, null);
        while (cursorUser.moveToNext()) {
            String doctorName = cursorUser.getString(1);
            String doctorPhone = cursorUser.getString(2);
            String doctorIdNumber = cursorUser.getString(8);
            String doctorAddress = cursorUser.getString(9);
            Integer doctorSex = null,doctorAge = null,doctorId = null;
            try {
                doctorSex = Integer.valueOf(cursorUser.getString(6));
                doctorAge = Integer.valueOf(cursorUser.getString(7));
                doctorId = Integer.valueOf(cursorUser.getString(10));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Log.e("DockerUpdateActivity.java", "数据不能转化为数字,请检查！");
            }
            doctorVo = new DoctorVo();
            doctorVo.setDoctorId(doctorId);
            doctorVo.setDoctorName(doctorName);
            doctorVo.setPhone(doctorPhone);
            doctorVo.setAge(doctorAge);
            doctorVo.setSex(doctorSex);
            doctorVo.setIdNumber(doctorIdNumber);
            doctorVo.setAddress(doctorAddress);
        }
//        判断基础信息是否存在
        if (Objects.nonNull(doctorVo)) {
//            提取出医生ID
            Integer doctorId = doctorVo.getDoctorId();
//            根据医生ID查询医生详情
            Cursor queryDoctor = readableDatabase.query("doctor_details", null, "id = ? ", new String[]{doctorId.toString()}, null, null, null);
            Integer positionId = null,departmentsId = null;
            while (queryDoctor.moveToNext()) {
                String specialty = queryDoctor.getString(4);
                String describe = queryDoctor.getString(5);
                try {
                    positionId = Integer.valueOf(queryDoctor.getString(2));
                    departmentsId = Integer.valueOf(queryDoctor.getString(3));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    Log.e("DockerAdminActivity.java", "数据不能转化为数字,请检查！");
                }
                doctorVo.setSpecialty(specialty);
                doctorVo.setDescribe(describe);
            }
            String positionName = null,departmentsName = null;
            if (positionId != null && departmentsId != null) {
//            根据职务ID查询医生职务
                Cursor queryPosition = readableDatabase.query("position", null, "id = ? ", new String[]{positionId.toString()}, null, null, null);
                while (queryPosition.moveToNext()) {
                    positionName = queryPosition.getString(1);
                }
//              根据科室ID查询医生所在科室名称
                Cursor queryDepartments = readableDatabase.query("departments", null, "id = ? ", new String[]{departmentsId.toString()}, null, null, null);
                while (queryDepartments.moveToNext()) {
                    departmentsName = queryDepartments.getString(1);
                }
                doctorVo.setPositionName(positionName);
                doctorVo.setDepartmentsName(departmentsName);
            } else {
                toast = ToastUtil.toastHint(toast, DockerAdminActivity.this, "暂时没有找到医生对应职务或所属科室，请稍后查看！");
                return;
            }
            intent = new Intent(DockerAdminActivity.this,DoctorUpdateActivity.class);
            Bundle bundle = new Bundle();
            String toJSONString = JSON.toJSONString(doctorVo);
            bundle.putString("doctorVo",toJSONString);
            intent.putExtras(bundle);
            startActivity(intent);
            DockerAdminActivity.this.finish();
            return;
        }
        toast = ToastUtil.toastHint(toast, DockerAdminActivity.this, "医生基本信息不存在，请稍后查看！");
        return;



    }

    /**
     * 按钮点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.doctorAddBtn:
                intent = new Intent(DockerAdminActivity.this, DoctorAddActivity.class);
                startActivity(intent);
                DockerAdminActivity.this.finish();
                break;
            default:
        }
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}